// miniprogram/pages/addDevice/index.js
const app = getApp();
const WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;
const SmartConfigPlug = require('qcloud-iotexplorer-appdev-plugin-wificonf-smartconfig');
const {
 // 错误的中文描述
 WifiConfErrorMsg, 
 // 步骤code
 WifiConfStepCode, 
 // 步骤code的中文描述 
 WifiConfStepDesp
} = WifiConfConstants;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    stepNum:1,
    ssid:null,
    bssid:null,
    token:null,
    password:'',
    inputType:true,
    progress:[
      { step:1,des:'手机与设备连接成功', successed:false },
      { step:2,des:'向设备发送信息成功', successed:false },
      { step:3,des:'设备连接云端成功', successed:false },
      { step:4,des:'初始化成功', successed:false }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getToken();
    SmartConfigPlug.default.install(app.sdk);  //注册插件
  },
  
  //生成WiFi设备配网token
  getToken: async function(){
    let that = this;
    app.sdk.init().then(()=>{
      app.sdk.requestApi('AppCreateDeviceBindToken')
      .then((res)=>{
        that.setData({ token:res.Token })
      })
      .catch((err)=>{
        console.log(err);
      })
    })
  },

  //获取WiFi信息
  getWifiInfo: function(){
    let that = this
    wx.getConnectedWifi({
      success(res) {
        console.log("getConnectedWifi ok:", JSON.stringify(res))
        if ('getConnectedWifi:ok' === res.errMsg) {
          that.setData({
            ssid: res.wifi.SSID,
            bssid: res.wifi.BSSID
          })
        } else {
          wx.showToast({
            title: '请连接路由器',
            duration: 2000,
            icon: 'none'
          })
        }
      }, fail(res) {
        wx.showToast({
          title: '请连接路由器',
          duration: 2000,
          icon: 'none'
        })
      }
    })
  },

  //下一步
  goNext:function(){
    let stepNum = this.data.stepNum;
    stepNum++;
    this.setData({ stepNum:stepNum });
  },

  //密码输入事件
  inputPwd:function(e){
    let that = this;
    that.setData({ password:e.detail.value });
  },

  //密码显隐
  changeType:function(){
    let inputType = this.data.inputType;
    inputType = !inputType;
    this.setData({ inputType:inputType });
  },

  //一键配网
  smartConfig:function(){ 
    let that = this;
    if (that.data.password.trim() === '') {
      wx.showToast({
        title: '请输入WiFi密码',
        icon:'error'
      })
      return;
    }
    let stepNum = this.data.stepNum;
    stepNum++;
    let wifiInfo = {  
      SSID:that.data.ssid,
      password:that.data.password,
      BSSID:that.data.bssid
    };

    let progress = that.data.progress;
    let onStepChange = (step)=>{
      progress[step-1].successed = true;
      that.setData({ progress:progress })
    }

      const onProgress = (data) => {
        // reporter.info(data.code, data.detail);

        switch (data.code) {
          case WifiConfStepCode.PROTOCOL_SUCCESS:
            onStepChange(1);
            break;
          case WifiConfStepCode.CREATE_UDP_CONNECTION_SUCCESS:
            onStepChange(2);
            break;
          case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
            onStepChange(3);
            break;
          case WifiConfStepCode.WIFI_CONF_SUCCESS:
            onStepChange(4);
            break;
        }
      };
      const onComplete = ({ productId, deviceName }) => {
        console.log('成功');
        wx.setStorageSync('wifiInfo', wifiInfo);
        wx.showToast({
          title: '绑定成功',
          duration:1500,
          success:()=>{
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        })
        // onStatusChange({
        //   status: 'success',
        //   productId,
        //   deviceName,
        // });
      };
      const onError = async ({ code, detail }) => {
        console.log('fail');
            wx.showToast({
              title: '绑定失败',
              icon:'error',
              mask:true,
            })
        stepNum--;
        that.setData({ stepNum:stepNum });
        // reporter.error(code, detail);

        // onStatusChange({ status: 'error' });
      };
    app.sdk.init().then(()=>{
      that.setData({ stepNum:stepNum });
      app.sdk.plugins['wifiConfSmartConfig'].start({
          wifiConfToken: that.data.token,
          targetWifiInfo: wifiInfo,
          autoRetry: true, // 自动处理故障流程
          familyId: 'default',
          onProgress,
          onError,
          onComplete
      });
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    wx.startWifi({
      success(res) {
        console.log(res.errMsg, 'wifi初始化成功')
        that.getWifiInfo();
      },
      fail: function () {
        wx.showToast({
          title: '请连接路由器!',
          duration: 2000,
          icon: 'none'
        })
      }
    })
    this.getWifiInfo();
    const wifi_Info = wx.getStorageSync('wifiInfo') || {};
    if((wifi_Info !== null) && (wifi_Info.SSID === this.data.ssid)){
      this.setData({ 
        password:wifi_Info.password,
        disableButton:false,
        });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})